package com.algorithm.base.backtracking;

import java.util.*;

/**
 * 90. 子集 II
 *
 * @author Amadeus
 * @date 2023/11/09
 */
public class SubsetsWithDup {

    static List<List<Integer>> result = new ArrayList<>();
    static Deque<Integer> deque = new LinkedList<>();

    public static List<List<Integer>> subsetsWithDup(int[] nums) {
        Arrays.sort(nums);
        int[] used = new int[nums.length + 1];
        backTracking(0, nums, used);
        return new ArrayList<>(result);
    }

    public static void backTracking(int index, int[] nums, int[] used) {
        result.add(new ArrayList<>(deque));

        for (int i = index; i < nums.length; i++) {
            if (i > 0 && nums[i] == nums[i - 1] && used[i - 1] == 0) {
                continue;
            }
            deque.addLast(nums[i]);
            used[i] = 1;
            backTracking(i + 1, nums, used);
            deque.removeLast();
            used[i] = 0;
        }
    }

    public static void main(String[] args) {
        subsetsWithDup(new int[]{1,2,2,3});
    }

}
